<template>
  <div class="message" :class="{ 'message-user': isUser }">
    <div class="message-wrapper">
      <div class="avatar">
        <img v-if="isUser" src="/用户.svg" class="avatar-img" alt="用户头像" />
        <img v-else src="/logo.svg" class="avatar-img" alt="AI头像" />
      </div>
      <div class="content">
        <div class="text-container">
          <button v-if="isUser" class="user-copy-button" @click="copyContent" :title="copyButtonTitle">
            <DocumentDuplicateIcon v-if="!copied" class="copy-icon" />
            <CheckIcon v-else class="copy-icon copied" />
          </button>
          <div class="text" ref="contentRef" v-if="isUser">
            {{ message.content }}
          </div>
          <div class="text markdown-content" ref="contentRef" v-else v-html="processedContent"></div>
        </div>
        <div class="message-footer" v-if="!isUser && !isSystemMessage">
          <div class="action-buttons">
            <button class="action-btn copy-btn" @click="copyContent" :title="copyButtonTitle">
              <img src="/复制.svg" alt="复制" class="action-icon" />
            </button>
            <button class="action-btn regenerate-btn" @click="regenerateMessage" title="重新生成">
              <img src="/重新生成.svg" alt="重新生成" class="action-icon" />
            </button>
            <button class="action-btn like-btn" @click="likeMessage" :class="{ 'active': liked }" title="赞">
              <img src="/赞.svg" alt="赞" class="action-icon" />
            </button>
            <button class="action-btn dislike-btn" @click="dislikeMessage" :class="{ 'active': disliked }" title="踩">
              <img src="/踩.svg" alt="踩" class="action-icon" />
            </button>
            <button class="action-btn delete-btn" @click="deleteMessage" title="删除">
              <img src="/删除.svg" alt="删除" class="action-icon" />
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, onBeforeUnmount, nextTick, ref, watch } from 'vue'
import { marked } from 'marked'
import DOMPurify from 'dompurify'
import { UserCircleIcon, ComputerDesktopIcon, DocumentDuplicateIcon, CheckIcon } from '@heroicons/vue/24/outline'
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark.css'

const contentRef = ref(null)
const copied = ref(false)
const liked = ref(false)
const disliked = ref(false)

const copyButtonTitle = computed(() => copied.value ? '已复制' : '复制内容')

// 配置 marked
marked.setOptions({
  breaks: true,
  gfm: true,
  sanitize: false
})

// 处理内容
const processContent = (content) => {
  if (!content) return ''

  // 分析内容中的 think 标签
  let result = ''
  let isInThinkBlock = false 
  let currentBlock = ''

  // 逐字符分析，处理 think 标签
  for (let i = 0; i < content.length; i++) {
    if (content.slice(i, i + 7) === '<think>') {
      isInThinkBlock = true
      if (currentBlock) {
        // 将之前的普通内容转换为 HTML
        result += marked.parse(currentBlock)
      }
      currentBlock = ''
      i += 6 // 跳过 <think>
      continue
    }

    if (content.slice(i, i + 8) === '</think>') {
      isInThinkBlock = false
      // 将 think 块包装在特殊 div 中
      result += `<div class="think-block">${marked.parse(currentBlock)}</div>`
      currentBlock = ''
      i += 7 // 跳过 </think>
      continue
    }

    currentBlock += content[i]
  }

  // 处理剩余内容
  if (currentBlock) {
    if (isInThinkBlock) {
      result += `<div class="think-block">${marked.parse(currentBlock)}</div>`
    } else {
      result += marked.parse(currentBlock)
    }
  }

  // 净化处理后的 HTML
  const cleanHtml = DOMPurify.sanitize(result, {
    ADD_TAGS: ['think', 'code', 'pre', 'span'],
    ADD_ATTR: ['class', 'language']
  })
  
  // 在净化后的 HTML 中查找代码块并添加复制按钮
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = cleanHtml
  
  // 查找所有代码块
  const preElements = tempDiv.querySelectorAll('pre')
  preElements.forEach(pre => {
    const code = pre.querySelector('code')
    if (code) {
      // 创建包装器
      const wrapper = document.createElement('div')
      wrapper.className = 'code-block-wrapper'
      
      // 添加复制按钮
      const copyBtn = document.createElement('button')
      copyBtn.className = 'code-copy-button'
      copyBtn.title = '复制代码'
      copyBtn.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" class="code-copy-icon" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
        </svg>
      `
      
      // 添加成功消息
      const successMsg = document.createElement('div')
      successMsg.className = 'copy-success-message'
      successMsg.textContent = '已复制!'
      
      // 组装结构
      wrapper.appendChild(copyBtn)
      wrapper.appendChild(pre.cloneNode(true))
      wrapper.appendChild(successMsg)
      
      // 替换原始的 pre 元素
      pre.parentNode.replaceChild(wrapper, pre)
    }
  })
  
  return tempDiv.innerHTML
}

// 修改计算属性
const processedContent = computed(() => {
  if (!props.message.content) return ''
  return processContent(props.message.content)
})

// 为代码块添加复制功能
const setupCodeBlockCopyButtons = () => {
  if (!contentRef.value) return;
  
  const codeBlocks = contentRef.value.querySelectorAll('.code-block-wrapper');
  codeBlocks.forEach(block => {
    const copyButton = block.querySelector('.code-copy-button');
    const codeElement = block.querySelector('code');
    const successMessage = block.querySelector('.copy-success-message');
    
    if (copyButton && codeElement) {
      // 移除旧的事件监听器
      const newCopyButton = copyButton.cloneNode(true);
      copyButton.parentNode.replaceChild(newCopyButton, copyButton);
      
      // 添加新的事件监听器
      newCopyButton.addEventListener('click', async (e) => {
        e.preventDefault();
        e.stopPropagation();
        try {
          const code = codeElement.textContent || '';
          await navigator.clipboard.writeText(code);
          
          // 显示成功消息
          if (successMessage) {
            successMessage.classList.add('visible');
            setTimeout(() => {
              successMessage.classList.remove('visible');
            }, 2000);
          }
        } catch (err) {
          console.error('复制代码失败:', err);
        }
      });
    }
  });
}

// 在内容更新后手动应用高亮和设置复制按钮
const highlightCode = async () => {
  await nextTick()
  if (contentRef.value) {
    contentRef.value.querySelectorAll('pre code').forEach((block) => {
      hljs.highlightElement(block)
    })
    
    // 设置代码块复制按钮
    setupCodeBlockCopyButtons()
  }
}

const props = defineProps({
  message: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['regenerate', 'like', 'dislike', 'delete'])

const isUser = computed(() => props.message.role === 'user')

// 判断是否为系统消息（问候语或系统提示）
const isSystemMessage = computed(() => {
  if (!props.message.content) return false

  // 检查是否包含系统消息的特征内容
  const systemKeywords = [
    '请输入您需要计算的问题',
    '材料的力学性能分析',
    '热力学计算等',
    '请输入您需要设计的内容',
    '请输入您需要合成的材料',
    '请输入您需要的工业推荐',
    '请输入您需要的结构设计',
    '请输入您需要的材料智能体'
  ]

  return systemKeywords.some(keyword => props.message.content.includes(keyword))
})

// 复制内容到剪贴板
const copyContent = async () => {
  try {
    // 获取纯文本内容
    let textToCopy = props.message.content;
    
    // 如果是AI回复，需要去除HTML标签
    if (!isUser.value && contentRef.value) {
      // 创建临时元素来获取纯文本
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = processedContent.value;
      textToCopy = tempDiv.textContent || tempDiv.innerText || '';
    }
    
    await navigator.clipboard.writeText(textToCopy);
    copied.value = true;
    
    // 3秒后重置复制状态
    setTimeout(() => {
      copied.value = false;
    }, 3000);
  } catch (err) {
    console.error('复制失败:', err);
  }
}

// 监听内容变化
watch(() => props.message.content, () => {
  if (!isUser.value) {
    highlightCode()
  }
})

// 初始化时也执行一次
onMounted(() => {
  if (!isUser.value) {
    highlightCode()
  }
})

// 重新生成消息
const regenerateMessage = () => {
  // 触发父组件的重新生成事件
  emit('regenerate', props.message)
}

// 点赞消息
const likeMessage = () => {
  liked.value = !liked.value
  if (liked.value && disliked.value) {
    disliked.value = false // 点赞时取消踩
  }
  emit('like', props.message, liked.value)
}

// 踩消息
const dislikeMessage = () => {
  disliked.value = !disliked.value
  if (disliked.value && liked.value) {
    liked.value = false // 踩时取消点赞
  }
  emit('dislike', props.message, disliked.value)
}

// 删除消息
const deleteMessage = () => {
  emit('delete', props.message)
}





const formatTime = (timestamp) => {
  if (!timestamp) return ''
  return new Date(timestamp).toLocaleTimeString()
}
</script>

<style scoped lang="scss">
.message {
  display: flex;
  justify-content: flex-start; // 默认AI消息靠左
  margin-bottom: 1.5rem;
  width: 100%;
  animation: messageSlideIn 0.4s ease-out;
  transform-origin: center;
  position: relative;

  .message-wrapper {
    display: flex;
    max-width: none; // 移除最大宽度限制，让消息可以延伸到红线
    width: 100%;
    gap: 1rem; // 默认间距
    padding: 0 4rem; // 左右留4rem空白，符合红框标示的留白比例
    box-sizing: border-box;

    @media (max-width: 768px) {
      max-width: none; // 移动端也移除最大宽度限制
      padding: 0 2rem; // 移动端左右留2rem空白
    }

    .avatar {
      width: 32px;
      height: 32px;
      flex-shrink: 0;
      margin-top: 0.5rem;
      border: none; // 确保容器没有边框
      border-radius: 0; // 确保容器没有圆角
      box-shadow: none; // 确保容器没有阴影
      background: transparent; // 确保容器背景透明

      .avatar-img {
        width: 100%;
        height: 100%;
        border-radius: 0; // 去掉圆形边框，改为方形
        object-fit: cover;
        border: none; // 去掉白色圆形边框
        box-shadow: none; // 确保图片没有阴影
        background: transparent; // 确保图片背景透明
      }
    }

    .content {
      display: flex;
      flex-direction: column;
      gap: 0.25rem;
      flex: 1;
      min-width: 0;

      .text-container {
        position: relative;
        width: 100%;
      }

      .text {
        padding: 0.8rem 0;
        line-height: 1.6; // 设置合适的行间距，确保文字不会挤在一起
        white-space: pre-wrap;
        font-size: 0.95rem;
        word-wrap: break-word;
        width: 100%;
        box-sizing: border-box;
        background: transparent;
        border: none;
        box-shadow: none;
      }

      .message-footer {
        display: flex;
        align-items: center;
        margin-top: 0.5rem;
        justify-content: flex-start;

        .action-buttons {
          display: flex;
          align-items: center;
          gap: 0.5rem;

          .action-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 28px;
            height: 28px;
            background: transparent;
            border: none;
            border-radius: 50%;
            cursor: pointer;
            transition: all 0.2s ease;
            opacity: 0.7;

            &:hover {
              background-color: rgba(0, 0, 0, 0.05);
              opacity: 1;
              transform: scale(1.1);
            }

            &.active {
              background-color: rgba(30, 136, 229, 0.1);
              opacity: 1;
            }

            .action-icon {
              width: 16px;
              height: 16px;
              object-fit: contain;
            }
          }

          // 删除按钮特殊样式 - 悬停时变红色
          .delete-btn {
            &:hover {
              background-color: rgba(255, 68, 68, 0.1); // 红色背景
              opacity: 1;
              transform: scale(1.1);

              .action-icon {
                // 将删除图标变为红色
                filter: brightness(0) saturate(100%) invert(27%) sepia(96%) saturate(7471%) hue-rotate(3deg) brightness(103%) contrast(97%);
              }
            }
          }

          .like-btn.active .action-icon,
          .dislike-btn.active .action-icon {
            filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(346deg) brightness(104%) contrast(97%);
          }

          .more-dropdown {
            position: relative;
            display: inline-block;

            .more-btn {
              display: flex;
              align-items: center;
              justify-content: center;
              height: 28px;
              padding: 0 8px;
              background: transparent;
              border: none;
              border-radius: 14px;
              cursor: pointer;
              transition: all 0.2s ease;
              opacity: 0.7;

              &:hover {
                background-color: rgba(0, 0, 0, 0.05);
                opacity: 1;
              }

              .more-text {
                font-size: 12px;
                color: #666;
                white-space: nowrap;
              }
            }

            .more-menu {
              position: absolute;
              top: 100%;
              right: 0;
              margin-top: 4px;
              background: white;
              border: 1px solid #e9ecef;
              border-radius: 8px;
              box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
              z-index: 1000;
              min-width: 120px;

              .more-menu-item {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 8px 12px;
                cursor: pointer;
                transition: background-color 0.2s ease;
                font-size: 14px;
                color: #333;

                &:hover {
                  background-color: #f8f9fa;
                }

                &:first-child {
                  border-radius: 8px 8px 0 0;
                }

                &:last-child {
                  border-radius: 0 0 8px 8px;
                }

                .more-icon {
                  width: 16px;
                  height: 16px;
                  object-fit: contain;
                }
              }
            }
          }
        }
      }
    }
  }

  &.message-user {
    justify-content: flex-end; // 用户消息靠右对齐

    .message-wrapper {
      flex-direction: row-reverse;
      padding-left: 6rem; // 用户消息左侧留更多空白，符合红框比例
      padding-right: 7rem; // 右侧适当留白
      gap: 0; // 完全消除头像和消息框之间的间距

      @media (max-width: 768px) {
        padding-left: 3rem; // 移动端用户消息左侧留3rem空白
        padding-right: 7rem; // 右侧适当留白
        gap: 0; // 移动端也完全贴合
      }
    }

    .content {
      align-items: flex-end;
      // 移除固定最大宽度，让消息框完全根据内容自适应

      .text-container {
        position: relative;
        display: inline-block; // 让容器根据内容自适应宽度
        max-width: none; // 移除最大宽度限制，让文字自由显示
        width: auto; // 自动宽度，根据内容调整
        margin-right: 0.3rem; // 在用户头像和消息之间添加额外间距

        @media (max-width: 768px) {
          max-width: 90%; // 移动端设置一个较大的限制，避免超出屏幕
          margin-right: 0.3rem; // 移动端稍微减少间距
        }

        .text {
          background: linear-gradient(135deg, #e3f2fd 0%, #f0f7ff 100%);
          color: #1565c0;
          border: 1px solid rgba(30, 136, 229, 0.15);
          box-shadow: 0 2px 8px rgba(30, 136, 229, 0.1);
          border-radius: 1rem; // 统一圆角，无尾巴设计
          padding: 0.6rem 1rem;
          font-weight: 500;
          position: relative;
          display: inline-block; // 让文本框根据内容自适应宽度
          width: auto; // 自动宽度
          min-width: auto; // 自动最小宽度
          max-width: 100%;
          word-wrap: break-word;
          font-size: 0.9rem;
          line-height: 1.4;
          white-space: nowrap; // 强制保持一行显示，不自动换行
          overflow: visible; // 允许内容溢出，不隐藏
          word-break: keep-all; // 保持单词完整
        }

        // 移除尾巴，让消息框直接与头像对齐

        .user-copy-button {
          position: absolute;
          left: -35px; // 恢复到合适的位置，无尾巴设计
          top: 50%;
          transform: translateY(-50%);
          background: rgba(30, 136, 229, 0.1);
          border: 1px solid rgba(30, 136, 229, 0.2);
          border-radius: 50%;
          width: 28px;
          height: 28px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          opacity: 0;
          transition: all 0.2s ease;

          &:hover {
            background: rgba(30, 136, 229, 0.15);
            transform: translateY(-50%) scale(1.1);
          }

          .copy-icon {
            width: 16px;
            height: 16px;
            color: #1e88e5;

            &.copied {
              color: #4ade80;
            }
          }
        }

        &:hover .user-copy-button {
          opacity: 1;
        }
      }

      .message-footer {
        flex-direction: row-reverse;
      }
    }
  }

  &:not(.message-user) {
    .message-wrapper {
      padding-right: 6rem; // AI消息右侧留更多空白，符合红框比例
      padding-left: 10rem; // 左侧适当留白

      @media (max-width: 768px) {
        padding-right: 3rem; // 移动端AI消息右侧留3rem空白
        padding-left: 0.5rem; // 左侧适当留白
      }
    }

    // 添加微妙的左侧指示线，表示AI消息
    &::after {
      content: '';
      position: absolute;
      left: 1rem;
      top: 50%;
      transform: translateY(-50%);
      width: 3px;
      height: 60%;
      background: rgba(108, 117, 125, 0.2);
      border-radius: 2px;
      opacity: 0.5;
    }

    .content {
      .text-container {
        .text {
          background: transparent;
          color: #333;
          border: none;
          box-shadow: none;
          border-radius: 0;
        }
      }
    }
  }

  .text {
    padding: 1.2rem 1.5rem;
    line-height: 1.3; // 减少行间距，避免过大的空白
    white-space: pre-wrap;
    font-size: 0.95rem;
    word-wrap: break-word;
    width: 100%;
    box-sizing: border-box;

      .cursor {
        animation: blink 1s infinite;
      }

      :deep(.think-block) {
        position: relative;
        padding: 0.75rem 1rem 0.75rem 1.5rem;
        margin: 0.5rem 0;
        color: #666;
        font-style: italic;
        border-left: 4px solid #ddd;
        background-color: rgba(0, 0, 0, 0.03);
        border-radius: 0 0.5rem 0.5rem 0;

        // 添加平滑过渡效果
        opacity: 1;
        transform: translateX(0);
        transition: opacity 0.3s ease, transform 0.3s ease;

        &::before {
          content: '思考';
          position: absolute;
          top: -0.75rem;
          left: 1rem;
          padding: 0 0.5rem;
          font-size: 0.75rem;
          background: #f5f5f5;
          border-radius: 0.25rem;
          color: #999;
          font-style: normal;
        }

        // 添加进入动画
        &:not(:first-child) {
          animation: slideIn 0.3s ease forwards;
        }
      }

      :deep(pre) {
        background: #f6f8fa;
        padding: 1rem;
        border-radius: 0.5rem;
        overflow-x: auto;
        margin: 0.5rem 0;
        border: 1px solid #e1e4e8;

        code {
          background: transparent;
          padding: 0;
          font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;
          font-size: 0.9rem;
          line-height: 1.5;
          tab-size: 2;
        }
      }

      :deep(.hljs) {
        color: #24292e;
        background: transparent;
      }

      :deep(.hljs-keyword) {
        color: #d73a49;
      }

      :deep(.hljs-built_in) {
        color: #005cc5;
      }

      :deep(.hljs-type) {
        color: #6f42c1;
      }

      :deep(.hljs-literal) {
        color: #005cc5;
      }

      :deep(.hljs-number) {
        color: #005cc5;
      }

      :deep(.hljs-regexp) {
        color: #032f62;
      }

      :deep(.hljs-string) {
        color: #032f62;
      }

      :deep(.hljs-subst) {
        color: #24292e;
      }

      :deep(.hljs-symbol) {
        color: #e36209;
      }

      :deep(.hljs-class) {
        color: #6f42c1;
      }

      :deep(.hljs-function) {
        color: #6f42c1;
      }

      :deep(.hljs-title) {
        color: #6f42c1;
      }

      :deep(.hljs-params) {
        color: #24292e;
      }

      :deep(.hljs-comment) {
        color: #6a737d;
      }

      :deep(.hljs-doctag) {
        color: #d73a49;
      }

      :deep(.hljs-meta) {
        color: #6a737d;
      }

      :deep(.hljs-section) {
        color: #005cc5;
      }

      :deep(.hljs-name) {
        color: #22863a;
      }

      :deep(.hljs-attribute) {
        color: #005cc5;
      }

      :deep(.hljs-variable) {
        color: #e36209;
      }
  }
}

// Markdown内容样式
.markdown-content {
  :deep(p) {
    margin: 0.5rem 0;

    &:first-child {
      margin-top: 0;
    }

    &:last-child {
      margin-bottom: 0;
    }
  }

  :deep(ul),
  :deep(ol) {
    margin: 0.5rem 0;
    padding-left: 1.5rem;
  }

  :deep(li) {
    margin: 0.25rem 0;
  }

  :deep(code) {
    background: rgba(0, 0, 0, 0.05);
    padding: 0.2em 0.4em;
    border-radius: 3px;
    font-size: 0.9em;
    font-family: ui-monospace, monospace;
  }

  :deep(pre code) {
    background: transparent;
    padding: 0;
  }

  :deep(table) {
    border-collapse: collapse;
    margin: 0.5rem 0;
    width: 100%;
  }

  :deep(th),
  :deep(td) {
    border: 1px solid #ddd;
    padding: 0.5rem;
    text-align: left;
  }

  :deep(th) {
    background: rgba(0, 0, 0, 0.05);
  }

  :deep(blockquote) {
    margin: 0.5rem 0;
    padding-left: 1rem;
    border-left: 4px solid #ddd;
    color: #666;
  }

  :deep(.code-block-wrapper) {
    position: relative;
    margin: 1rem 0;
    border-radius: 6px;
    overflow: hidden;

    .code-copy-button {
      position: absolute;
      top: 0.5rem;
      right: 0.5rem;
      background: rgba(255, 255, 255, 0.1);
      border: none;
      color: #e6e6e6;
      cursor: pointer;
      padding: 0.25rem;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity 0.2s, background-color 0.2s;
      z-index: 10;

      &:hover {
        background-color: rgba(255, 255, 255, 0.2);
      }

      .code-copy-icon {
        width: 16px;
        height: 16px;
      }
    }

    &:hover .code-copy-button {
      opacity: 0.8;
    }

    pre {
      margin: 0;
      padding: 1rem;
      background: #1e1e1e;
      overflow-x: auto;

      code {
        background: transparent;
        padding: 0;
        font-family: ui-monospace, monospace;
      }
    }

    .copy-success-message {
      position: absolute;
      top: 0.5rem;
      right: 0.5rem;
      background: rgba(74, 222, 128, 0.9);
      color: white;
      padding: 0.25rem 0.5rem;
      border-radius: 4px;
      font-size: 0.75rem;
      opacity: 0;
      transform: translateY(-10px);
      transition: opacity 0.3s, transform 0.3s;
      pointer-events: none;
      z-index: 20;

      &.visible {
        opacity: 1;
        transform: translateY(0);
      }
    }
  }
}

@keyframes blink {
  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0;
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-10px);
  }

  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes messageSlideIn {
  from {
    opacity: 0;
    transform: translateY(20px) scale(0.95);
  }

  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}


</style>